package com.share.four.netty.heartBeat;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import com.share.four.netty.heartBeat.entity.ReqInfo;

public class ClientHandler extends ChannelHandlerAdapter{
	
	ScheduledExecutorService schedulerThreadPool = Executors.newScheduledThreadPool(1);

	public static final String AUTH_SUCCESS = "auth success!";
	public static final String AUTH_FAIL = "auth fail!";

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("client channel active");

		InetAddress localHost = InetAddress.getLocalHost();
		String ip = localHost.getHostAddress();
		String key = "12345";
		String auth = ip + "," + key;
		ctx.writeAndFlush(auth);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {

		try {
			String resp = (String)msg;
			if (AUTH_SUCCESS.equals(resp)) {
				schedulerThreadPool.scheduleWithFixedDelay(new HeartBeatTask(ctx), 0, 5, TimeUnit.SECONDS);
				System.out.println(resp);
			} else {
				System.out.println(resp);
			}

		} finally {
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
	
	
	
	/**
	 * 内部类
	 */
	private class HeartBeatTask implements Runnable{
		
		private ChannelHandlerContext ctx;

		public HeartBeatTask(ChannelHandlerContext ctx) {
			super();
			this.ctx = ctx;
		}

		@Override
		public void run() {
			try {
				
				ReqInfo reqInfo = new ReqInfo();
				String ip = InetAddress.getLocalHost().getHostAddress();
				
				Sigar sigar = new Sigar();
				
				CpuPerc cpuPerc = sigar.getCpuPerc();
				HashMap<String, Object> cpuInfo = new HashMap<>();
				cpuInfo.put("CPU系统使用率：", CpuPerc.format(cpuPerc.getSys()));
				cpuInfo.put("CPU当前等待率：", CpuPerc.format(cpuPerc.getWait()));
				cpuInfo.put("CPU当前错误率：", CpuPerc.format(cpuPerc.getNice()));
				cpuInfo.put("CPU当前空闲率：", CpuPerc.format(cpuPerc.getIdle()));
				cpuInfo.put("CPU总的使用率：", CpuPerc.format(cpuPerc.getCombined()));
				
				Mem mem = sigar.getMem();
				HashMap<String, Object> memoryInfo = new HashMap<>();
				memoryInfo.put("内存总量：", mem.getTotal()/1024 + "K av"); 
				memoryInfo.put("当前内存使用量：", mem.getUsed()/1024 + "K used"); 
				memoryInfo.put("当前内存剩余量：", mem.getFree()/1024 + "K free"); 

				reqInfo.setIp(ip);
				reqInfo.setCupInfo(cpuInfo);
				reqInfo.setMemoryInfo(memoryInfo);
				
				ctx.writeAndFlush(reqInfo);
				
			} catch (Exception e) {
				System.out.println(e);
			}
			
		}
	}
	
	

}
